<?php
//TODO this element is not finished
/**
 * Defines Kodform_Element_Reset class
 *
 *
 * Kodform.php - kodform4
 * @copyright 	Copyright (c) 2006 Boris Tomic (kodmasin.net)
 * @category 	Kodform
 * @package 	Kodform
 * @author 		Boris Tomic
 * @license 	http://boris.kodmasin.net/kodform4:license The BSD License
 *
 */

/**
 * implements option element. That is set of radio buttons so that user
 * can select one. 
 */
class Kodofrm_Element_Option extends Kodform_Element{
	protected $values;
	const horizontalStyle = 0;
	const verticalStyle = 0;
	protected $dstyle;
	protected $error;
	function __construct($id, $displayName, $required, $error){
		parent::__construct($id, null, $required);
		$this->setDisplayName($displayName);
		$this->values = array();
		$this->error = $error;
		$this->dstyle = Kodofrm_Element_Option::verticalStyle;
	}
	function addValue($value, $display){
		$this->values[$value] = $display;
	}
	public function setDisplayStyle($styleType = Kodofrm_Element_Option::verticalStyle){
		$this->dstyle = $styleType;
	}
	public function display(Kodform_Attributes $attributes = null){
		$style = "";
		if($attributes == null)
			$attributes = new Kodform_Attributes();
		$attr = $attributes->normal;
		if($this->isRequired())
			$attr = $attributes->required;
		if(!$this->isValid())
			$attr = $attributes->error;
		$style .= $attr->display();
		$str = "<fieldset style=\"" . $style . "\" id=\"" . $this->id . "\"><legend>" . $this->displayName . "</legend>";
		$elem = "<input type=\"radio\" name=\"" . $this->id . "\" value=\"" . $value . "\"";
		if($dstyle == Kodofrm_Element_Option::horizontalStyle){
			foreach($values as $value => $display){
				if($value == $this->getValue())
					$elem .= " checked=\"checked\"";
				$elem .= " />";
				$str .= $elem . $display . " "; 
			}
		}
		else{
			foreach($values as $value => $display){
				if($value == $this->getValue())
					$elem .= " checked=\"checked\"";
				$elem .= " />";
				$str .= "<div>" . $elem . $display . "</div>";
			} 
		}
		$str .= "</fieldset>";
	}
	public function validate(){
		$valid = true;
		//check if form is submited
		if($this->form != null && $this->form->isSubmited()){
			$this->rawValue = $this->form->getRaw($this->id);//get raw submited data
			if($this->required != null){//if required do required validation
				if(!$this->required->validate($this->rawValue)){
					//$valid = false;
					array_push($this->errors, $this->required->getError());
					return false;
				}
			}
			if(!array_key_exists($this->rawValue, $this->values)){
				$valid = false;
				array_push($this->errors, $this->error);
			}
		}
		if($valid)
				$this->validValue = $this->rawValue;
		return $valid;
	}
}